# Clean up
rm(list = ls())

# Set working directory; please set your own here
setwd("~/Desktop/fragmentation_replication_bjps/")

library(tidyverse)
library(foreign)
library(cowplot)

# Import data with main analyses
data <- read.dta("Results/analyses_final.dta")

# Subset 2SLS results
iv_results <- data %>%
  filter(Sample == "Whole") %>%
  filter(id == "No. parties just above")  %>%
  filter(Predictor == "ENPP")

# Fix one outcome label
iv_results$Outcome[iv_results$Outcome == "Summary\nmeasures (PCA)"] <- "Summary\\nmeasures (PCA)"

# Subset OLS results
ols_results <- data %>%
  filter(Model == "OLS") %>%
  filter(Predictor == "ENPP")

# Write function to compare coefficients in OLS and 2SLS
compare_coefs <- function(outcome){
  # check means
  mean_ols <- mean(ols_results$Effect[ols_results$Outcome == outcome])
  mean_iv <- mean(iv_results$Effect[iv_results$Outcome == outcome])
  
  message('OLS coefficient:')
  print(mean_ols)
  
  # check p-value in OLS
  pval_ols <- mean(ols_results$pval[ols_results$Outcome == outcome])
  
  message('OLS p-value:')
  print(format(pval_ols, scientific = FALSE))
  
  message('Mean 2SLS coefficient:')
  print(mean_iv)
  
  # calculate proportion
  #proportion_iv_ols <- abs(mean_iv) / abs(mean_ols)
  proportion_iv_ols <- mean_iv / mean_ols
  
  message('Proportion 2SLS / OLS:')
  print(proportion_iv_ols)
  
}

table(iv_results$Outcome)
# Compare for each outcome
compare_coefs("Summary\\nmeasures (PCA)")
compare_coefs("Participatory Dem index (Vdem)")
compare_coefs("Liberal Dem index (Vdem)")
compare_coefs("Electoral Dem index (Vdem)")
compare_coefs("Egalitarian Dem index (Vdem)")
compare_coefs("Deliberative Dem index (Vdem)")

compare_coefs("Accountability (PCA)")
compare_coefs("Vertical accountability index")
compare_coefs("Horizontal accountability index")
compare_coefs("Diagonal accountability index")

compare_coefs("Corruption (PCA)")
compare_coefs("Public sector corruption")
compare_coefs("Legislature corruption")
compare_coefs("Executive embezzlement/theft")
compare_coefs("Executive bribery/corruption")

compare_coefs("Descriptive repr women (PCA)")
compare_coefs("Power distributed by gender")
compare_coefs("Percent female MPs")

compare_coefs("Index government fractionalization")
compare_coefs("Distance next election")

compare_coefs("Repr underpriviliged\\ngroups (PCA)")
compare_coefs("Representation disadvantaged groups")
compare_coefs("Power distr by social groups")
compare_coefs("Power distr by sexual orientation")

compare_coefs("Turnout")
compare_coefs("Provision public goods")